<template>
    <div class="app-container">
        <div v-show="show === 'rule'">
            <div class="filter-container">
                <div class="filter-item block">
                    <el-date-picker
                            size="medium"
                            v-model="query.eat_date"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择订餐时间">
                    </el-date-picker>
                </div>
                <el-select class="filter-item w-200" clearable v-model="query.school_id" size="medium" placeholder="请选择学校">
                    <el-option
                            v-for="item in schools"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
                <el-select class="filter-item w-200" clearable v-model="query.eat_type" size="medium" placeholder="请选择订餐类型">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-select class="filter-item w-200" clearable v-model="query.is_cancel" size="medium" placeholder="状态">
                    <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-select class="filter-item w-200" clearable v-model="query.is_settled" size="medium" placeholder="是否结算">
                    <el-option
                            v-for="item in settleOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(true)">搜 索</el-button>
            </div>
            <el-table v-loading="loading" :data="bookRules" border style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-table :data="scope.row.prices" border :show-summary="scope.row.is_settled===1" style="width: 100%">
                            <el-table-column width="100px" label="#" align="center">
                                <template slot-scope="props" >
                                    {{query.size * (query.page-1) + props.$index + 1}}
                                </template>
                            </el-table-column>
                            <el-table-column label="条目名称" align="center">
                                <template slot-scope="props">
                                    {{ props.row.category.name }}
                                </template>
                            </el-table-column>
                            <el-table-column label="条目描述" align="center">
                                <template slot-scope="props">
                                    {{ props.row.category.description }}
                                </template>
                            </el-table-column>
                            <el-table-column label="成本(元)" prop="total_price" align="center"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column width="100px" label="#" align="center">
                    <template slot-scope="scope" >
                        {{query.size * (query.page-1) + scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column label="所属学校" prop="school.name" width="250px" align="center"></el-table-column>
                <el-table-column prop="eat_date" label="订餐时间" width="200px" align="center"></el-table-column>
                <el-table-column prop="eat_type" label="订餐类型" width="150px" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.eat_type === 1">早餐</div>
                        <div v-if="scope.row.eat_type === 2">午餐</div>
                        <div v-if="scope.row.eat_type === 3">晚餐</div>
                    </template>
                </el-table-column>
                <el-table-column label="菜品" align="center">
                    <template slot-scope="scope">
                        <span v-for="(food,index) in scope.row.foods" :key="food.id">{{ index === 0 ? food.name : ', ' + food.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="count" label="订餐人数" width="150px" align="center"></el-table-column>
                <el-table-column label="总价(元)" width="150px" align="center">
                    <template slot-scope="scope" >
                        {{ getTotalPrice(scope.row) }}
                    </template>
                </el-table-column>
                <el-table-column label="实付总金额(元)" width="150px" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.is_settled === 1 ? scope.row.totalPayPrice : null }}
                    </template>
                </el-table-column>
                <el-table-column label="是否启用" width="100px" align="center">
                    <template slot-scope="scope" >
                        <i class="el-icon-check" v-if="scope.row.is_cancel === 0" />
                        <i class="el-icon-close" v-else />
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="更新时间" width="250px" align="center"></el-table-column>
                <el-table-column label="操作" width="250px" align="center">
                    <template slot-scope="scope">
                        <el-button class="filter-item" icon="el-icon-view" type="primary" size="mini" @click="showOrders(scope.row)">查看订单</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="query.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="query.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>
        </div>

        <div v-show="show === 'order'">
            <div class="filter-container">
                <el-input v-model="queryOrder.eat_name" class="filter-item w-200" size="medium" placeholder="吃饭人姓名"></el-input>
                <el-input v-model="queryOrder.eat_phone" class="filter-item w-200" size="medium" placeholder="吃饭人电话"></el-input>
                <el-select class="filter-item w-200" size="medium" v-model="queryOrder.price_rule" clearable placeholder="计费规则">
                    <el-option label="固定餐标" value="1"></el-option>
                    <el-option label="计算餐标" value="2"></el-option>
                    <el-option label="计全额" value="3"></el-option>
                </el-select>
                <el-select class="filter-item w-200" size="medium" v-model="queryOrder.is_calculated" clearable placeholder="是否结算餐费">
                    <el-option label="已结算" value="1"></el-option>
                    <el-option label="未结算" value="0"></el-option>
                </el-select>
                <el-select class="filter-item w-200" size="medium" v-model="queryOrder.status" clearable placeholder="订单状态">
                    <el-option label="已提交" value="10"></el-option>
                    <el-option label="制作中" value="20"></el-option>
                    <el-option label="已完成" value="30"></el-option>
                    <el-option label="已取消" value="40"></el-option>
                </el-select>
                <el-select class="filter-item w-200" size="medium" v-model="queryOrder.orderType" clearable placeholder="订单类型">
                    <el-option label="正常订单" value="normal"></el-option>
                    <el-option label="加餐订单" value="addition"></el-option>
                    <el-option label="公务订单" value="official"></el-option>
                </el-select>
                <el-button class="filter-item" type="primary" size="medium" icon="el-icon-search" @click="fetchOrderList(true)">搜索</el-button>
                <el-button class="filter-item" size="medium" icon="el-icon-download" @click="downloadOrder()">导出订单</el-button>
                <el-button class="filter-item" type="primary" style="float: right" size="medium" icon="el-icon-search" @click="showRule">返回</el-button>
            </div>

            <el-table v-loading="loading2" :data="bookOrders" border style="width: 100%">
                <el-table-column width="100px" label="#" align="center">
                    <template slot-scope="scope" >
                        {{queryOrder.size * (queryOrder.page-1) + scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column prop="eat_name" label="吃饭人姓名" align="center"></el-table-column>
                <el-table-column prop="eat_phone" label="吃饭人电话" align="center"></el-table-column>
                <el-table-column label="订餐类型" align="center">
                    <template slot-scope="scope" >
                        <span v-if="scope.row.rule.eat_type === 1">早餐</span>
                        <span v-if="scope.row.rule.eat_type === 2">午餐</span>
                        <span v-if="scope.row.rule.eat_type === 3">晚餐</span>
                    </template>
                </el-table-column>
                <el-table-column label="订餐时间" align="center">
                    <template slot-scope="scope" >
                        {{ scope.row.rule.eat_date }}
                    </template>
                </el-table-column>
                <el-table-column label="计费规则" align="center">
                    <template slot-scope="scope" >
                        {{ scope.row.price_rule ? (scope.row.price_rule === 1 ? '固定餐标' : (scope.row.price_rule === 2 ? '计算餐标' : '计全额')) : '' }}
                    </template>
                </el-table-column>
                <el-table-column label="是否结算餐费" align="center">
                    <template slot-scope="scope" >
                        <i class="el-icon-check" v-if="scope.row.is_calculated === 1" />
                        <i class="el-icon-close" v-else />
                    </template>
                </el-table-column>
                <el-table-column prop="origin_price" label="原价(元)" align="center"></el-table-column>
                <el-table-column prop="pay_price" label="实际支付价格(元)" align="center"></el-table-column>
                <el-table-column label="是否自动产生订单" align="center">
                    <template slot-scope="scope" >
                        <i class="el-icon-check" v-if="scope.row.is_auto === 1" />
                        <i class="el-icon-close" v-else />
                    </template>
                </el-table-column>
                <el-table-column prop="type_label" label="订单类型" align="center"></el-table-column>
                <el-table-column label="订单状态" align="center">
                    <template slot-scope="scope" >
                        <span v-if="scope.row.status === 10">已提交</span>
                        <span v-if="scope.row.status === 20">制作中</span>
                        <span v-if="scope.row.status === 30">已完成</span>
                        <span v-if="scope.row.status === 40">已取消</span>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="下单时间" width="160px" align="center"></el-table-column>
                <el-table-column prop="making_at" label="制作时间" width="160px" align="center"></el-table-column>
                <el-table-column prop="finished_at" label="完成时间" width="160px" align="center"></el-table-column>
                <el-table-column prop="canceled_at" label="取消时间" width="160px" align="center"></el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination
                        @size-change="handleOrderSizeChange"
                        @current-change="handleOrderCurrentChange"
                        :current-page="queryOrder.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="queryOrder.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalOrder">
                </el-pagination>
            </div>
        </div>

    </div>
</template>

<script>
  import { fetchBookRule, fetchBookOrder } from '@/api/book-rule'
  import { fetchSchools } from '@/api/data'
  export default {
    name: 'list',
    data() {
      return {
        show: 'rule',
        loading: false,
        loading2: false,
        bookRules: [],
        schools: [],
        bookOrders: [],
        total: 0,
        totalOrder: 0,
        query: {
          eat_date: '',
          eat_type: '',
          size: 10,
          page: 1,
          status: 1,
          rule_id: '',
          is_settle: false,
          is_settled: '',
          is_cancel: '',
          school_id: ''
        },
        queryOrder: {
          type: '',
          size: 10,
          page: 1,
          status: '',
          eat_name: '',
          eat_phone: '',
          is_calculated: '',
          price_rule: '',
          rule_id: '',
          school_id: '',
          orderType: ''
        },
        options: [
          {
            value: 1,
            label: '早餐'
          },
          {
            value: 2,
            label: '午餐'
          },
          {
            value: 3,
            label: '晚餐'
          }
        ],
        statusOptions: [
          {
            value: 1,
            label: '取消'
          },
          {
            value: 0,
            label: '启用'
          }
        ],
        settleOptions: [
          {
            value: 1,
            label: '已结算'
          },
          {
            value: 0,
            label: '未结算'
          }
        ],
        settleTitle: ''
      }
    },
    methods: {
      showRule() {
        this.show = 'rule'
        this.queryOrder.status = ''
        this.queryOrder.eat_name = ''
        this.queryOrder.eat_phone = ''
        this.queryOrder.is_calculated = ''
        this.queryOrder.price_rule = ''
      },
      // 订单列表筛选
      fetchOrderList(resetPage = false) {
        this.queryOrder.type = ''
        this.loading2 = true
        if (resetPage === true) {
          this.queryOrder.page = 1
        }
        fetchBookOrder(this.queryOrder).then(res => {
          this.bookOrders = res.data
          this.totalOrder = res.meta.total
          this.loading2 = false
        })
      },
      // 显示订餐规则下的订单
      showOrders(row) {
        this.queryOrder.type = ''
        this.show = 'order'
        this.loading2 = true
        this.queryOrder.rule_id = row.id
        this.queryOrder.school_id = row.school_id
        fetchBookOrder(this.queryOrder).then(res => {
          this.bookOrders = res.data
          this.totalOrder = res.meta.total
          this.loading2 = false
        })
      },
      // 订餐规则列表
      fetchList(resetPage = false) {
        this.loading = true
        if (resetPage === true) {
          this.query.page = 1
        }
        fetchBookRule(this.query).then(res => {
          this.bookRules = res.data
          this.total = res.meta.total
          this.loading = false
        })
      },
      // 获取当前学校id
      getSchoolInfo() {
        this.fetchList()
      },
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      handleOrderSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleOrderCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      getTotalPrice(row) {
        let cost = 0
        for (let i = 0; i < row.prices.length; i++) {
          cost += row.prices[i].total_price
        }
        return cost
      },
      // 导出订单
      downloadOrder() {
        this.$confirm('确定导出?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.exportOrder(this.queryOrder)
        }).catch(() => {})
      },
      exportOrder(row) {
        row.type = 'export'
        fetchBookOrder(row).then(res => {
          if (res.length === 0) {
            this.$message('无数据')
          } else {
            const filename = this.$moment().format('YYYY-MM-DD') + '-' + parseInt(10000 * Math.random())
            const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' }
            const list = res
            const tHeader = ['学校', '吃饭人姓名', '吃饭人电话', '订餐类型', '订餐日期', '原价', '实际支付价格', '是否结算餐费', '计算规则', '订单类型', '订单状态', '下单时间', '制作时间', '完成时间', '取消时间']
            const filterVal = ['school_name', 'eat_name', 'eat_phone', 'eat_type', 'eat_date', 'origin_price', 'pay_price', 'is_calculate', 'rule_name', 'type_label', 'status_label', 'created_at', 'making_at', 'finished_at', 'canceled_at']
            const data = this.formatJson(filterVal, list)
            data.unshift(tHeader)
            const wb = { SheetNames: [], Sheets: {}}
            const ws = this.sheet_from_array_of_arrays(data)
            ws['!cols'] = []
            for (let n = 0; n !== filterVal.length; ++n) {
              ws['!cols'].push({
                wpx: 100
              })
            }
            ws['!rows'] = [{ hpx: 20 }]
            wb.SheetNames.push(filename)
            wb.Sheets[filename] = ws
            const tmpDown = new Blob([this.s2ab(this.$xlsx.write(wb, wopts))], { type: 'application/octet-stream' })
            this.$fileSaver.saveAs(tmpDown, filename + '.xlsx')
          }
        })
      },
      sheet_from_array_of_arrays(data) {
        const ws = {}
        const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 }}
        for (let R = 0; R !== data.length; ++R) {
          for (let C = 0; C !== data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R
            if (range.s.c > C) range.s.c = C
            if (range.e.r < R) range.e.r = R
            if (range.e.c < C) range.e.c = C
            const cell = {
              v: data[R][C],
              s: {
                alignment: { horizontal: 'center', vertical: 'center' }
              }
            }
            if (cell.v == null) continue
            const cell_ref = this.$xlsx.utils.encode_cell({ c: C, r: R })
            if (typeof cell.v === 'number') {
              cell.t = 'n'
            } else if (typeof cell.v === 'boolean') {
              cell.t = 'b'
            } else if (cell.v instanceof Date) {
              cell.t = 'n'
              cell.z = this.$xlsx.SSF._table[14]
              cell.v = this.datenum(cell.v)
            } else {
              cell.t = 's'
            }
            ws[cell_ref] = cell
          }
        }
        if (range.s.c < 10000000) ws['!ref'] = this.$xlsx.utils.encode_range(range)
        return ws
      },
      datenum(v, date1904) {
        if (date1904) v += 1462
        const epoch = Date.parse(v)
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
      },
      s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }
    },
    created() {
      this.getSchoolInfo()
      fetchSchools().then(res => {
        this.schools = res.schools
      })
    }
  }
</script>

<style scoped>
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
